import sys
import pymssql
from PyQt5.QtCore import Qt
import socket

import smtplib
from email.mime.text import MIMEText
from PyQt5.QtWidgets import QApplication, QMessageBox, QMainWindow, QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMenu, QAction, QMessageBox
from public import dbhelper
from PyQt5.QtWidgets import QDesktopWidget, QHBoxLayout
from PyQt5.QtCore import QCoreApplication
import requests
import psutil
import socket
import wmi
from public import write_log, getaccountinfo
from PyQt5.QtCore import pyqtSignal
import pymysql
from qtsif import TAsin
from qtamz import TCrawl
import time
import re


class MainWindow(QMainWindow):
    custom_signal = pyqtSignal(str)

    def __init__(self):

        super().__init__()
        self.initUI()

    def initUI(self):

        file_path = './output.txt'

        # with open(file_path, 'w') as f:
        #     # os.system(f'attrib +h "{file_path}"')
        #     # 将标准输出重定向到文件对象
        #     original_stdout = sys.stdout
        #     sys.stdout = f
        #     print('这行内容将会输出到 2output.txt 文件中。')
        #     # 恢复标准输出
        #     sys.stdout = original_stdout

        self.login_window = None

        desktop = QDesktopWidget()

        screen_rect = desktop.screenGeometry()

        percentage = 0.80

        self.setWindowTitle("欢迎使用选品系统，使用步骤注册->登录-> 使用选品系统")

        width = int(screen_rect.width() * percentage)
        height = int(screen_rect.height() * percentage)
        self.resize(width, height)
        self.userdata = {}

        accountinfo = getaccountinfo()
        databasetype = accountinfo['databasetype']
        self.dbconn = None

        if databasetype.lower() != 'mysql':
            print('a23c')
            self.dbconn = dbhelper()
            print('a23d')
            datefunction = 'getdate()'
        else:
            datefunction = 'now()'
            print('a23')
            self.dbconn = dbhelper(server='gz-cdb-pr3j7lhn.sql.tencentcdb.com',
                                   uid='root',
                                   pwd='Zb_200407',
                                   database='amazon',
                                   port=26590,
                                   creator=pymysql)

        c = wmi.WMI()
        self.disknumber = ''

        for x in c.Win32_DiskDrive():
            self.disknumber += x.SerialNumber + ' '
            # print(f"硬盘编号：{x.SerialNumber}")

        self.gateway = self.get_gateway()
        #         if self.gateway:
        #             print(f"网关地址是：{self.gateway}")
        #             aaa = 32
        #         else:
        #             print("未找到网关地址。")
        #           aaa=32

        self.ip = 'no ip'
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            self.ip = s.getsockname()[0]
            s.close()
        except Exception as e:
            print(f"Error getting local IP: {e}")

        print('22')
        self.userdata = {
            'gateway': self.gateway,
            'ip': self.ip,
            'disknumber': self.disknumber,
            'dbconnection': self.dbconn,
            'databasetype': databasetype,
            'datefunction': 'now()',
            'debug': 1
        }
        print('23')
        menubar = self.menuBar()
        operation_menu = menubar.addMenu('操作')
        register_action = QAction('注册', self)
        register_action.triggered.connect(self.show_registration_window)
        login_action = QAction('登录', self)
        login_action.triggered.connect(self.show_login_window)

        crawl_action = QAction('抓取capture', self)
        crawl_action.triggered.connect(self.show_crawl_window)

        choose_action = QAction('选品', self)
        choose_action.triggered.connect(self.show_choosegoods_window)

        operation_menu.addAction(register_action)
        operation_menu.addAction(login_action)
        operation_menu.addAction(crawl_action)
        operation_menu.addAction(choose_action)
        self.show_login_window()

    def closeEvent(self, event):

        if hasattr(self, 'registration_window') and self.registration_window:
            self.registration_window.close()
        if hasattr(self, 'login_window') and self.login_window:
            self.login_window.close()
        super().closeEvent(event)

    def update_value(self, value):
        # 这里可以根据实际情况更新主窗口中的值
        print(f"主窗口接收到的值：{value}")

    def receive_value(self, value):
        self.userdata['username'] = value
        print(f"Received value from child: {value}")

    def get_gateway(self):

        gateways = psutil.net_if_addrs()

        for interface, addresses in gateways.items():
            for address in addresses:
                if address.family == socket.AF_INET and address.address != '127.0.0.1':
                    if address.netmask == '255.255.255.0':
                        # 尝试不同的方式获取可能的网关信息
                        for route in psutil.net_connections(kind='inet'):
                            if route.laddr.ip == address.address:
                                return route.raddr.ip if route.raddr else None

    def show_registration_window(self):
        self.registration_window = RegistrationWindow(self.userdata)
        self.registration_window.show()

    def show_crawl_window(self):

        self.crawl_window = TCrawl(self.userdata)
        self.crawl_window.show()
        main_center_x = self.geometry().center().x()
        main_center_y = self.geometry().center().y()
        self.login_window.move(
            main_center_x - int(self.login_window.width() / 2),
            main_center_y - int(self.login_window.height() / 2))

    def show_login_window(self):

        self.login_window = LoginWindow(self.userdata)
        self.login_window.value_changed.connect(self.receive_value)
        self.login_window.show()
        main_center_x = self.geometry().center().x()
        main_center_y = self.geometry().center().y()
        self.login_window.move(
            main_center_x - int(self.login_window.width() / 2),
            main_center_y - int(self.login_window.height() / 2))
        # 设置子窗口位置使其位于主窗口中心

    def show_choosegoods_window(self):
        self.choosegoods_window = TAsin(self.userdata)
        self.choosegoods_window.show()

    def receive_value(self, value):
        self.userdata['username'] = value
        str = f"接收到窗口 login 的值：{self.userdata['username']}"
        print(str)


class RegistrationWindow(QWidget):
    regusername_signal = pyqtSignal(str)

    def __init__(self, data):

        super().__init__()

        self.userdata = data
        layout = QVBoxLayout()
        self.close_button = QPushButton('关闭')
        self.close_button.clicked.connect(self.close_window)
        self.setWindowFlags(Qt.Dialog)

        # self.close_button = QPushButton('去登录')
        # self.close_button.clicked.connect(self.loginwindow)
        desktop = QDesktopWidget()
        screen_rect = desktop.screenGeometry()
        percentage = 0.60
        self.setWindowTitle("选品系统->登录")

        width = int(screen_rect.width() * percentage)
        height = int(screen_rect.height() * percentage)
        self.resize(width, height)

        label = QLabel('这是注册窗口。')
        self.username_label = QLabel("用户名<span style='color:red'>*</span>：")
        self.username_reg = QLineEdit()
        self.username_reg.setText('')
        self.email_label = QLabel("邮箱<span style='color:red'>*</span>：")
        self.email_reg = QLineEdit()
        self.email_reg.setText('')
        self.phone_label = QLabel("手机号码<span style='color:red'>*</span>：")
        self.phone_reg = QLineEdit()
        self.phone_reg.setText('')  # 假设的测试数据
        self.password_label = QLabel("密码<span style='color:red'>*</span>：")
        self.password_reg = QLineEdit()
        self.password_reg.setText('')  # 假设的测试数据
        self.password_reg.setEchoMode(QLineEdit.Password)
        self.register_button = QPushButton('注册')
        self.register_button.clicked.connect(self.register)
        layout.addWidget(label)
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_reg)
        layout.addWidget(self.email_label)
        layout.addWidget(self.email_reg)
        layout.addWidget(self.phone_label)
        layout.addWidget(self.phone_reg)
        layout.addWidget(self.password_label)
        layout.addWidget(self.password_reg)
        layout.addWidget(self.register_button)
        layout.addWidget(self.close_button)

        self.setLayout(layout)

    def register(self):
        username = self.username_reg.text()
        email = self.email_reg.text()
        phone = self.phone_reg.text()
        password = self.password_reg.text()

        try:
            # 连接到 MS SQL Server
            dbo = self.userdata['dbconnection']
            sql = f"select * from US_USERS where username='{username}' or phone='{phone}'"
            rows = dbo.dbread_data(sql)
            # 插入用户信息到 US_USERS 表
            msgstr = ''
            interr = 0
            if password == '' or username == '' or email == '' or phone == '':
                msgstr += f'所有输入项必须填写.\n'
                interr += 1
            email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
            if not bool(re.match(email_pattern, email)):
                msgstr += f'邮箱格式不对，：{email}格式不正确.\n'
                interr += 1
            # 判断手机号码

            phone_pattern = r'^1[3-9]\d{9}$'
            if not bool(re.match(phone_pattern, phone)):
                msgstr += f'手机格式不对，：{phone}格式不正确.'
                interr += 1

            if interr > 0:
                QMessageBox.warning(self, '格式填写错误！', msgstr)

            if len(rows) > 0:
                QMessageBox.warning(
                    self, '注册失败',
                    f'注册时出现错误：{username}或者{phone},{email}其中某一个项信息已经存在,您可以考虑联系492524133@qq.com找回密码,或者重新注册'
                )
                interr += 1

            if interr == 0:
                sql = f"INSERT INTO US_USERS (opdate,Username, Email, phone, Password,ip,gateway) VALUES ({self.userdata['datefunction']},'{username}', '{email}', '{phone}', '{password}','{self.userdata['ip']}','{self.userdata['gateway']}')"
                dbo.dbexecute(sql)
                self.send_email(email)
                QMessageBox.information(self, '注册成功', f'用户 {username} 注册成功！')
                self.userdata['username'] = username
                self.choosegoods_window = TAsin(self.userdata)
                self.choosegoods_window.show()
                #此时可以进入选品窗口
                # self.parent_window.userdata['username'] = username
                # self.parent_window.show_choosegoods_window(self.userdata)
                self.userdata['action'] = 'register'
                self.userdata['memo'] = ''
                write_log(self.userdata['dbconnection'], self.userdata, None)
                self.close()
        except Exception as e:
            QMessageBox.warning(self, '注册失败', f'注册时出现错误：{str(e)}')
        finally:
            #
            a = 2

    def send_email(self, receiver_email):
        sender = '492524133@qq.com'
        msg = MIMEText('欢迎注册！')
        msg['Subject'] = '注册成功通知'
        msg['From'] = sender
        msg['To'] = receiver_email

        try:
            s = smtplib.SMTP('smtp.qq.com', 587)
            # s.starttls()
            # s.login('492524133@qq.com', 'Zb@200407')
            # s.sendmail(sender, receiver_email, msg.as_string())
            # s.quit()
        except Exception as e:
            print(f"邮件发送失败：{str(e)}")

    def close_window(self):

        self.close()


class LoginWindow(QWidget):
    username_signal = pyqtSignal(str)
    value_changed = pyqtSignal(str)  # 定义一个信号，这里假设传递一个整数类型的值

    def __init__(self, data):

        super().__init__()

        percentage = 0.4
        self.setWindowTitle("欢迎使用选品系统，使用步骤注册->登录-> 使用选品系统")
        desktop = QDesktopWidget()
        screen_rect = desktop.screenGeometry()

        width = int(screen_rect.width() * percentage)
        height = int(screen_rect.height() * percentage * 0.4)
        self.resize(width, height)
        self.userdata = data
        self.setWindowTitle('选品系统登录窗口->请输入账号密码，去登录哦！')
        layout = QHBoxLayout()

        self.username_label = QLabel('用户名：')
        self.username_input = QLineEdit()
        layout.addWidget(self.username_label)
        layout.addWidget(self.username_input)
        # self.username_input.setText('q11')
        self.password_label = QLabel('密码：')
        self.password_input = QLineEdit()
        # self.password_input.setText('123456')
        self.password_input.setEchoMode(QLineEdit.Password)
        layout.addWidget(self.password_label)
        layout.addWidget(self.password_input)

        self.login_button = QPushButton('登录')
        self.login_button.clicked.connect(self.check_login)

        self.register_button = QPushButton('还没有账号去注册')
        self.register_button.clicked.connect(self.goregister)
        show_password_button = QPushButton("显示密码")
        show_password_button.clicked.connect(self.toggle_password_visibility)
        layout.addWidget(show_password_button)
        layout.addWidget(self.login_button)
        layout.addWidget(self.register_button)

        self.setLayout(layout)

    def toggle_password_visibility(self):
        if self.password_input.echoMode() == QLineEdit.Password:
            self.password_input.setEchoMode(QLineEdit.Normal)
        else:
            self.password_input.setEchoMode(QLineEdit.Password)

    def check_login(self):
        try:
            username = self.username_input.text()
            password = self.password_input.text()
            dbo = self.userdata['dbconnection']
            sql = f"SELECT * FROM us_users WHERE username='{username}' AND password='{password}'"
            rows = dbo.dbread_data(sql)
            if len(rows) > 0:
                sql = f"UPDATE us_users SET opdate={self.userdata['datefunction']}, ip='{self.userdata['ip']}',gateway='{self.userdata['gateway']}' WHERE username='{username}'"
                print(sql)
                dbo.dbexecute(sql)

                data = {}
                data['ip'] = self.userdata['ip']
                data['gateway'] = self.userdata['gateway']
                data['username'] = username
                data['action'] = 'login'
                data['memo'] = 'login'
                data['datefunction'] = self.userdata['datefunction']
                data['disknumber'] = self.userdata['disknumber']
                write_log(self.userdata['dbconnection'], data, None)

                self.userdata['username'] = username
                self.value_changed.emit(username)

                self.tasin = TAsin(self.userdata)
                self.tasin.show()
                time.sleep(0.3)
                self.close()

            else:
                print(f'登录失败:{username}或者密码错误！')
                QMessageBox.warning(self, '错误', f'登录失败:{username}或者密码错误！')
                return ''
        except Exception as e:
            print(f'登录失败:{e}！')

    def goregister(self):
        self.registration_window = RegistrationWindow(self.userdata)
        self.registration_window.show()
        self.close()

    def open_selection_window(self):
        # 这里假设选品窗口类名为 SelectionWindow
        a = 1
        a += 1
        print(a)


if __name__ == '__main__':
    try:
        app = QApplication(sys.argv)
        main_window = MainWindow()
        main_window.custom_signal.connect(main_window.update_value)

        main_window.show()
        app.exec_()
    except Exception as e:
        print(f"An error occurred: {e}")
